<template>
  <div class="course">
    <!-- 搜索部分 -->
    <el-row :gutter="10" class="search-section">
      <el-col :span="4">
        <el-form-item label="新闻标题：">
          <el-input v-model="filters.title" placeholder="请输入新闻标题"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-form-item label="图片路径：">
          <el-input v-model="filters.imageURL" placeholder="请输入图片路径"></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="4">
        <el-form-item label="排序：">
          <el-select v-model="filters.order" placeholder="请选择排序">
            <el-option label="正序" value="asc"></el-option>
            <el-option label="反序" value="desc"></el-option>
          </el-select>
        </el-form-item>

      </el-col>
      <el-col :span="4">
        <el-form-item label="作者：">
          <el-input v-model="filters.writer" placeholder="请输入作者"></el-input>
        </el-form-item>

      </el-col>
      <el-col :span="4">
        <el-form-item label="新闻简介：">
          <el-input v-model="filters.introduction" placeholder="请输入新闻简介"></el-input>
        </el-form-item>

      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="search" :icon="Search">搜索</el-button>
        <el-button @click="reset" :icon="Refresh">重置</el-button>
      </el-col>
    </el-row>

    <!-- 按钮部分 deleteSelectedNews-->
    <div class="button-section">
      <el-button type="primary" plain :icon="Plus" @click="openAddDialog">新增</el-button>
      <el-button type="success" plain :icon="Edit" @click="editSelectedNews">修改</el-button>
      <el-button type="danger" plain :icon="Delete" @click="deleteSelectedNews">删除</el-button>
      <el-button type="warning" plain :icon="Download" @click="exportExcle">导出</el-button>
    </div>

    <!-- 新闻列表表格 -->
    <el-table :data="newsListWithPagination" style="width: 100%" ref="multipleTable" @selection-change="handleSelectionChange">

      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="title" label="新闻标题"></el-table-column>
      <el-table-column prop="writer" label="作者" width="100"></el-table-column>
      <el-table-column prop="introduction" label="新闻简介"></el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template #default="scope">
          <div class="operation-buttons">
            <el-button type="primary" @click="editNews(scope.$index, scope.row)" link size="small"
              :icon="EditPen">修改</el-button>
            <el-button type="primary" @click="deleteNews(scope.$index, scope.row)" link size="small"
              :icon="Delete">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination class="pagination-fixed" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pageination.currentPage" :page-sizes="[10, 15, 20, 25, 30]" :page-size="pageination.pageSize"
        layout="total, sizes, prev, pager, next" :total="pageination.total"> <!--  style="text-align: center;" -->
      </el-pagination>
    </div>
    <!-- 添加资讯 -->
    <el-dialog v-model="visible" title="添加资讯" width="70%" @close="resetForm">
      <div>
        <el-form :model="addFormData" :rules="rules" ref="ruleForm">
          <el-form-item label="新闻标题" prop="title" style="width: 500px;">
            <el-input v-model="addFormData.title" placeholder="请输入新闻标题"></el-input>
          </el-form-item>
          <el-form-item label="封面图片" prop="image">
            <el-upload class="upload-demo" ref="upload" action="http://localhost:9000/upload"
              :on-preview="handlePreview" :on-remove="handleRemove" :before-remove="beforeRemove" :file-list="fileList"
              list-type="picture-card" :on-success="handleUploadSuccess" :limit="1" :on-exceed="handleExceed" draggable>

              <el-icon>
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item style="margin-top: 0px;">
            <div slot="tip" class="el-upload__tip" style="margin-left: 60px;">文件大小不超过 5MB, 支持 png/jpg/jpeg 格式
            </div>
          </el-form-item>
          <el-dialog v-model="dialogVisible" style="width: 480px; height: auto;">
            <img :src="dialogImageUrl" style="width: 400px; height: auto;" />
          </el-dialog>
          <el-form-item label="新闻简介" prop="introduction">
            <el-input v-model="addFormData.introduction" placeholder="请输入新闻简介"></el-input>

          </el-form-item>
          <el-form-item label="新闻内容" prop="content">
            <QuillEditorVue ref="quillEditor" :initial-content="addFormData.content"
              @content-updated="handleContentUpdate">
            </QuillEditorVue>

          </el-form-item>
          <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;作者" prop="writer">
            <el-input v-model="addFormData.writer" placeholder="请输入作者" style="width: 200px;"></el-input>
          </el-form-item>

          <el-form-item label="选择租户" prop="enterprise_name">
            <el-input v-model="addFormData.enterprise_name" placeholder="请输入企业名称" style="width: 200px;"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visible = false; resetForm()">取消</el-button>
          <el-button type="primary" @click="submitForm">提交</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 修改资讯 -->
    <el-dialog v-model="visibleUpdate" title="编辑资讯" width="70%" @close="resetForm">
      <div>
        <el-form :model="updateFormData" :rules="rules" ref="ruleForm">
          <el-form-item label="新闻标题" prop="title" style="width: 500px;">
            <el-input v-model="updateFormData.title" placeholder="请输入新闻标题"></el-input>
          </el-form-item>
          <el-form-item label="封面图片" prop="image">
            <el-upload class="upload-demo" ref="upload1" action="http://localhost:9000/upload"
              :on-preview="handlePreview1" :on-remove="handleRemove1" :before-remove="beforeRemove1"
              :file-list="fileList1" list-type="picture-card" :on-success="handleUploadSuccess1" :limit="1"
              :on-exceed="handleExceed1" draggable>
              <!-- 如果有图片URL，显示图片<el-icon><Plus /></el-icon> -->
              <img v-if="updateFormData.imageURL" :src="updateFormData.imageURL" class="avatar" />

            </el-upload>

          </el-form-item>
          <el-form-item style="margin-top: 0px;">
            <div slot="tip" class="el-upload__tip" style="margin-left: 60px;">文件大小不超过 5MB, 支持 png/jpg/jpeg 格式
            </div>
          </el-form-item>
          <el-dialog v-model="dialogVisible1" style="width: 480px; height: auto;">
            <img :src="dialogImageUrl1" style="width: 400px; height: auto;" />
          </el-dialog>
          <el-form-item label="新闻简介" prop="introduction">
            <el-input v-model="updateFormData.introduction" placeholder="请输入新闻简介"></el-input>

          </el-form-item>
          <el-form-item label="新闻内容" prop="content">
            <QuillEditorVue ref="quillEditor1" :initial-content="updateFormData.content"
              @content-updated="handleContentUpdate1">
            </QuillEditorVue>

          </el-form-item>
          <el-form-item label="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;作者" prop="writer">
            <el-input v-model="updateFormData.writer" placeholder="请输入作者" style="width: 200px;"></el-input>
          </el-form-item>

          <el-form-item label="选择租户" prop="enterprise_name">
            <el-input v-model="updateFormData.enterprise_name" placeholder="请输入企业名称" style="width: 200px;"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="visibleUpdate = false; resetForm()">取消</el-button>
          <el-button type="primary" @click="submitEditForm">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick, Ref, reactive, onMounted } from 'vue';
import { Plus, Edit, Delete, Download, EditPen, Search, Refresh } from '../../../node_modules/@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { type Filters, type NewsItem, getNewsList, editNew, exportFile, addNew, searchNews, deleteNew } from '../../api/newsApi.ts'
import QuillEditorVue from '../../components/commonUse/Editor.vue';
import type { UploadProps, UploadUserFile, UploadRawFile, FormInstance } from 'element-plus'
import axios from 'axios';
import router from '../../router/index.ts';
import { log } from 'console';
import { computed } from 'vue';
import { getUserList, type UserItem } from '../../api/userApi.ts';
import { getListCompany, CpyItem, type CompanyItem } from '../../api/companyApi.ts';
import { watch } from 'vue';

const filters: Ref<Filters> = ref({
  title: '',
  imageURL: '',
  order: 'asc',//默认正序
  writer: '',
  introduction: ''
});

const newsList: Ref<NewsItem[]> = ref([]);
const newsListWithPagination: Ref<NewsItem[]> = ref([]);

// 计算属性，根据排序方式动态排序新闻列表
const sortedNewsList = computed(() => {
  const copyNewsList = [...newsList.value];
  copyNewsList.sort((a, b) => {
    if (filters.value.order === 'desc') {
      return b.id - a.id; // 按照 id 进行正序排序
    } else {
      return a.id - b.id; // 按照 id 进行反序排序
    }
  });
  return copyNewsList;
});


const fetchNews = async () => {
  try {
    newsList.value = await getNewsList();
    pageination.total = newsList.value.length;
    handleCurrentChange(1);
    handleSizeChange(10);
  } catch (error) {

    console.error("Failed to fetch news:", error);
  }
};
fetchNews();
// 搜索功能
const search = async () => {
  const res = await searchNews(filters.value);
  newsList.value = res;
  ElMessage.success('搜索成功！');

};

//重置搜索条件
const reset = () => {
  filters.value = {
    title: '',
    imageURL: '',
    order: '',
    writer: '',
    introduction: ''
  };
  fetchNews();
  ElMessage.success('重置成功！');
};


//添加资讯
const visible = ref(false);

const addFormData = ref<NewsItem>({
  id: 0,
  title: '',
  content: '',
  imageURL: '',
  writer: '',
  introduction: '',
  enterprise_name: ''
});
const openAddDialog = () => {
  visible.value = true;
  resetForm(); // 如果需要重置表单
  fetchNews(); // 重新获取数据
};
//图片预览
const dialogImageUrl = ref('');
const dialogVisible = ref(false);
const upload = ref(); // 引用上传组件
const handlePreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url; // 确保设置正确的图片URL
  dialogVisible.value = true;
};
//更新富文本编辑器内容
const quillEditor = ref(null);
const handleContentUpdate = (newContent: string) => {
  addFormData.value.content = newContent;
}

//上传封面图片

const fileList: Ref<UploadRawFile[]> = ref([]);
const handleRemove = (file: any, fileList: any) => {
  //用户点击移除按钮,先执行beforeRemove1中的逻辑，再执行handleRemove1中的逻辑
  addFormData.value.imageURL = fileList.length > 0 ? fileList[0].url : '';
};
const beforeRemove = async (file: any, fileList: any) => {
  try {
    await ElMessageBox.confirm(`确定移除 ${file.name}？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    return true;
  } catch (e) {
    console.error('Remove cancelled', e);
    return false;
  }
};

const handleUploadSuccess = (response: any, file: any, fileList: any) => {
  addFormData.value.imageURL = response.data; // 假设 response.data 是图片 URL
  file.url = response.data; // 更新fileList中的文件URL，确保预览是正确的
};
// 超过文件限制处理函数
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value.clearFiles(); // 清除现有文件
  const newFile = files[0] as UploadRawFile;
  upload.value.handleStart(newFile); // 手动添加文件到上传队列
  fileList.value.push(newFile); // 更新文件列表
};
//表单验证
const users = ref<UserItem[]>([]);
const isShown = ref(false)//ELMessage解锁(创建者)
const isShownCom = ref(false)//ELMessage解锁(公司)
const companies = ref<CpyItem[]>([]);
onMounted(async () => {
  users.value = await getUserList();
  companies.value = await getListCompany();
});
const ruleForm = ref<FormInstance>()
const rules = {//tbc
  title: [
    { required: true, message: '请输入新闻标题！', trigger: 'blur' }
  ],
  introduction: [
    { required: true, message: '请输入新闻简介！', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入新闻内容！', trigger: 'blur' }
  ],
  writer: [
    { required: true, message: '请输入新闻作者！', trigger: 'blur' }
  ],
  enterprise_name: [
    { required: true, message: '请输入企业名称！', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any) => {
        console.log(companies.value)
        const isGet = ref(false);
        companies.value.forEach((company: CpyItem) => {
          if (company.company_name == value) {
            isGet.value = true;
            callback();
            return true;
          }
        })
        callback(new Error('输入的企业未注册'));
        if (isGet.value == false && isShownCom.value == false) {
          ElMessage({
            message: '输入的企业未注册！或者尝试刷新页面',
            type: 'error',
          });
          isShownCom.value = true;//ELMessage加锁
        }
      }, trigger: 'blur'
    }
  ]
};
// 实现提交功能
const submitForm = async () => {
  if (ruleForm.value) {
    ruleForm.value.validate(async (valid: any) => {
      if (valid) {
        try {
          await addNew(addFormData.value);
          ElMessage.success('提交成功！');
          visible.value = false;
          // 提交后清空表单
          resetForm();
          fetchNews();
          isShown.value = false//ELMessage解锁
          isShownCom.value = false
        } catch (error) {
          console.error('Login failed:', error)
          // 可以在这里添加错误处理，例如显示错误消息给用户
        }

      } else {
        ElMessage({
          message: '请提交正确的新闻资讯信息!',
          type: 'error',
        });
        return false;
      }
    });
  }
};



//修改资讯
const visibleUpdate = ref(false);
const updateFormData = ref<NewsItem>({
  id: 0,
  title: '',
  content: '',
  imageURL: '',
  writer: '',
  introduction: '',
  enterprise_name: ''
});
//更新富文本编辑器内容
const quillEditor1 = ref(null);
const handleContentUpdate1 = (newContent: string) => {

  updateFormData.value.content = newContent;

}
//上传封面图片
const fileList1: Ref<UploadRawFile[]> = ref([]);
//图片预览
const dialogImageUrl1 = ref('');
const dialogVisible1 = ref(false);
const upload1 = ref(); // 引用上传组件
const handlePreview1: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl1.value = uploadFile.url!;
  dialogVisible1.value = true;
};

//删除封面图片
const handleRemove1 = (file: any, fileList: any) => {
  //用户点击移除按钮,先执行beforeRemove1中的逻辑，再执行handleRemove1中的逻辑
  updateFormData.value.imageURL = fileList.length > 0 ? fileList[0].url : '';
};

const beforeRemove1 = async (file: any, fileList: any) => {
  try {
    await ElMessageBox.confirm(`确定移除 ${file.name}？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    return true;
  } catch (e) {
    console.error('Remove cancelled', e);
    return false;
  }
};

const handleUploadSuccess1 = (response: any, file: any, fileList: any) => {
  updateFormData.value.imageURL = response.data; // 假设 response.data 是图片 URL
  file.url = response.data; // 更新fileList中的文件URL
};

const handleExceed1: UploadProps['onExceed'] = (files) => {
  upload1.value.clearFiles(); // 清除现有文件
  const newFile = files[0] as UploadRawFile;
  upload1.value.handleStart(newFile); // 手动添加文件到上传队列
  fileList1.value.push(newFile); // 更新文件列表
};

//编辑
const editNews = async (index: number, row: NewsItem) => {
  visible.value = false;
  // 确保 Vue 的更新周期完成，确保所有数据被处理
  await nextTick();
  // 使用传入的行数据填充表单
  updateFormData.value = {
    ...row // 展开row对象，并将其值赋给addFormData.value
  };

  visibleUpdate.value = true;
};
//提交修改资讯的表单
const submitEditForm = async () => {

  if (ruleForm.value) {
    ruleForm.value.validate(async (valid: any) => {
      if (valid) {
        try {
          await editNew(updateFormData.value);
          ElMessage.success('修改成功！');

          visible.value = false;
          // 提交后清空表单
          resetForm();
          visibleUpdate.value = false;
          fetchNews();
          isShown.value = false//ELMessage解锁
          isShownCom.value = false
        } catch (error) {
          console.error('Login failed:', error)
          // 可以在这里添加错误处理，例如显示错误消息给用户
        }

      } else {
        ElMessage({
          message: '请提交正确的新闻资讯信息!',
          type: 'error',
        });
        return false;
      }
    });
  }



};

//重置表单
const resetForm = async () => {
  addFormData.value = {
    id: 0,
    title: '',
    content: '',
    imageURL: '',
    writer: '',
    introduction: '',
    enterprise_name: ''
  };
  // 清除上传组件的文件列表
  if (upload.value) {
    upload.value.clearFiles();
  }
  // 清除上传组件的文件列表
  if (upload1.value) {
    upload1.value.clearFiles();
  }
  updateFormData.value = {
    id: 0,
    title: '',
    content: '',
    imageURL: '',
    writer: '',
    introduction: '',
    enterprise_name: ''
  };

};
//删除资讯
const deleteNews = async (index: number, row: NewsItem) => {
  //获取新闻id
  const id = row.id;
  const title = row.title;
  ElMessageBox.confirm('确定删除该 "' + title + '" 的新闻吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteNew(id);
    console.log(`成功删除新闻 "${title}"`);
    ElMessage.success('删除成功！');
    fetchNews(); // 刷新新闻列表或执行其他操作
  }).catch(() => {
    ElMessage.info('已取消批量删除');
  });
};
//选择条目功能
//不能实现批量添加，删除，修改，只能对选中的第一条数据进行操作
//批量删除已经实现
const selectedRows = ref<NewsItem[]>([]);
const handleSelectionChange = (selection: NewsItem[]) => {
  selectedRows.value = selection;
};
const editSelectedNews = async () => {
  if (selectedRows.value.length === 0) {
    // 可能需要显示一个警告消息，说明没有选中任何行
    ElMessage.warning('请先选择要编辑的新闻');
    return;
  }
  //选取第一条选中的新闻进行删除
  const row = selectedRows.value[0];
  editNews(0, row);

};
const deleteSelectedNews = async () => {
  if (selectedRows.value.length === 0) {
    // 可能需要显示一个警告消息，说明没有选中任何行
    ElMessage.warning('请先选择要删除的新闻');
    return;
  }
  // 遍历选中的所有咨询条目，并逐个执行删除操作
  for (const row of selectedRows.value) {
    const title = row.title;
    const id = row.id;
    try {
      await deleteNew(id);

    } catch (error) {
      ElMessage.error('删除失败！');
    }
  }
  ElMessage.success('删除成功！');
  fetchNews(); // 刷新新闻列表
};
//导出excel
const exportExcle = () => {
  exportFile();
  ElMessage.success('导出成功！');
};


//分页
const pageination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 64
});

//当每页条数发生了变化，调用此函数
const handleSizeChange = (val: number) => {
  pageination.pageSize = val;
  newsListWithPagination.value = sortedNewsList.value.slice((pageination.currentPage - 1) * pageination.pageSize, Math.min((pageination.currentPage) * pageination.pageSize, pageination.total));
};
//当前页码发生变化，调用此函数
const handleCurrentChange = (val: number) => {
  pageination.currentPage = val;
  newsListWithPagination.value = sortedNewsList.value.slice((pageination.currentPage - 1) * pageination.pageSize, Math.min((pageination.currentPage) * pageination.pageSize, pageination.total));
};
// 监听 sortedNewsList 的值的变化
watch(sortedNewsList, () => {
  handleSizeChange(pageination.pageSize);
  handleCurrentChange(pageination.currentPage);
});

</script>

<style scoped>
.course {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 1200px;
  padding: 10px;
  margin: 0 auto;
}

.search-section {
  margin-bottom: 2px;
  width: 100%;
}

.button-section {
  margin-bottom: 10px;
  width: 100%;
  display: flex;
  justify-content: flex-start;
  gap: 10px;
}

.operation-buttons {
  display: flex;
  justify-content: space-between;
}

/* .pagination-fixed {
  position: fixed;
  right: 30px;
  bottom: 20px;
  z-index: 1000;
} */



.upload-demo .el-upload__tip {
  font-size: 12px;
  line-height: 1.0;
  margin-top: 0px;
}

.avatar-uploader-icon {
  border: 1px dashed var(--el-border-color);
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 158px;
  text-align: center;
}

.avatar {
  width: 100%;
  /* 根据需要调整尺寸 */
  height: auto;
  cursor: pointer;
}

.pagination-fixed {
  text-align: center;
}

.pagination-container {
  /* position: fixed; */
  display: flex;
  margin-top: 25px ;
  /* margin-bottom: -2000px; */
  justify-content: center;
  width: 100%;
  z-index: 1000;
  /* 确保分页条在最上层 */
}
</style>
